<template>
  <ToolbarButton
    icon="i-ri-links-line"
    title="链接"
    shortcut="Ctrl+K"
    :active="isActive"
    :large-icon="props.largeIcon"
    :hide-text="props.hideText"
    @click="handleClick"
  />

  <!-- 链接对话框 -->
  <Dialog
    v-model="showDialog"
    title="插入链接"
    width="420px"
    @close="handleCancel"
  >
    <el-form
      :model="{ linkText, linkType, linkUrl }"
      label-width="80px"
      size="small"
    >
      <el-form-item label="链接文本:">
        <el-input
          v-model="linkText"
          placeholder="显示的文字"
          @keyup.enter="handleConfirm"
        />
      </el-form-item>
      <el-form-item label="链接至:">
        <el-select v-model="linkType" placeholder="请选择" style="width: 100%">
          <el-option
            v-for="option in linkTypeOptions"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          >
            <div class="link-type-option-item">
              <i
                v-if="option.icon"
                :class="option.icon"
                class="link-type-option-icon"
              ></i>
              <span>{{ option.label }}</span>
            </div>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="链接地址:">
        <el-input
          v-model="linkUrl"
          type="url"
          placeholder="https://example.com"
          @keyup.enter="handleConfirm"
        />
      </el-form-item>
      <el-form-item v-if="currentLink">
        <div class="form-hint">当前链接: {{ currentLink }}</div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" :disabled="!isValidUrl" @click="handleConfirm">
        {{ isActive ? "更新" : "确定" }}
      </el-button>
      <el-button v-if="isActive" type="danger" @click="handleRemove">
        移除链接
      </el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, computed, inject, type Ref } from "vue";
import type { Editor } from "@tiptap/vue-3";
import type { EditorProps } from "../../../../types";
import ToolbarButton from "../../../button/index.vue";
import { Dialog } from "../../../dialog";
import { defaultDicts } from "../../../../config/constants";

defineOptions({
  name: "Link",
});

const props = withDefaults(
  defineProps<{
    largeIcon?: boolean;
    hideText?: boolean;
  }>(),
  {
    largeIcon: false,
    hideText: true,
  }
);

// 注入编辑器实例和配置
const editor = inject<Ref<Editor>>("editor");
const editorProps = inject<Ref<EditorProps>>("editorProps");

const isActive = computed(() => {
  return editor?.value?.isActive("link");
});

// 获取当前链接地址
const currentLink = computed(() => {
  if (!editor?.value?.isActive("link")) return null;
  const attrs = editor.value.getAttributes("link");
  return attrs.href || null;
});

// 获取当前选中的文本
const getSelectedText = () => {
  if (!editor?.value) return "";
  const { state } = editor.value;
  const { selection } = state;
  if (selection.empty) return "";
  return state.doc.textBetween(selection.from, selection.to);
};

// 获取当前链接的文本内容
const getCurrentLinkText = () => {
  if (!editor?.value || !isActive.value) return "";
  const { state } = editor.value;
  const { selection } = state;

  // 获取链接节点内的文本
  let text = "";
  state.doc.nodesBetween(selection.from, selection.to, (node) => {
    if (
      node.type.name === "text" &&
      node.marks.some((mark) => mark.type.name === "link")
    ) {
      text += node.text;
    }
  });
  return text || getSelectedText();
};

// 链接类型选项 - 从 editorProps.dicts.linkTypes 获取，如果没有则使用默认值
const linkTypeOptions = computed(() => {
  const linkTypes =
    editorProps?.value?.dicts?.linkTypes || defaultDicts.linkTypes || [];
  const locale = editorProps?.value?.locale || "zh-CN";
  return linkTypes.map((item: any) => {
    // 处理国际化标签，根据 locale 选择对应的语言
    let label: string;
    if (typeof item.label === "string") {
      label = item.label;
    } else if (typeof item.label === "object") {
      label =
        (locale === "zh-CN" ? item.label?.zh_CN : item.label?.en_US) ||
        item.label?.zh_CN ||
        item.label?.en_US ||
        item.value;
    } else {
      label = item.value;
    }
    return {
      label,
      value: item.value,
      icon: item.icon,
    };
  });
});

// 对话框状态
const showDialog = ref(false);
const linkUrl = ref("");
const linkText = ref("");
const linkType = ref<string>("web");

// 验证 URL 是否有效
const isValidUrl = computed(() => {
  if (!linkUrl.value.trim()) return false;
  try {
    new URL(linkUrl.value.trim());
    return true;
  } catch {
    // 如果不是完整的 URL，允许相对路径或协议相对路径
    return linkUrl.value.trim().length > 0;
  }
});

// 处理点击按钮
const handleClick = () => {
  // 获取当前选中的文本
  const selectedText = getSelectedText();

  // 如果已经有链接，获取当前链接地址和文本
  if (isActive.value && currentLink.value) {
    linkUrl.value = currentLink.value;
    linkText.value = getCurrentLinkText() || selectedText;
    // 根据链接地址判断类型（简化处理，暂时都设为第一个选项的值）
    linkType.value = linkTypeOptions.value[0]?.value || "web";
  } else {
    linkUrl.value = "";
    linkText.value = selectedText;
    linkType.value = linkTypeOptions.value[0]?.value || "web";
  }
  showDialog.value = true;
};

// 处理确认
const handleConfirm = () => {
  if (!isValidUrl.value || !editor?.value) return;

  const url = linkUrl.value.trim();
  const text = linkText.value.trim();

  // 如果没有协议，添加 https://
  let finalUrl = url;
  if (url && !url.match(/^[a-zA-Z][a-zA-Z\d+.-]*:/)) {
    finalUrl = `https://${url}`;
  }

  const { state } = editor.value;
  const { selection } = state;

  // 如果有文本且当前没有选中内容，或者有选中内容需要替换
  if (text) {
    if (selection.empty) {
      // 没有选中内容，插入新链接
      editor.value
        .chain()
        .focus()
        .insertContent(`<a href="${finalUrl}">${text}</a>`)
        .run();
    } else {
      // 有选中内容，替换为带链接的文本
      editor.value
        .chain()
        .focus()
        .deleteSelection()
        .insertContent(`<a href="${finalUrl}">${text}</a>`)
        .run();
    }
  } else {
    // 没有文本，直接设置链接（保留原文本）
    editor.value.chain().focus().setLink({ href: finalUrl }).run();
  }

  // 关闭对话框
  showDialog.value = false;
  linkUrl.value = "";
  linkText.value = "";
  linkType.value = linkTypeOptions.value[0]?.value || "web";
};

// 处理取消
const handleCancel = () => {
  showDialog.value = false;
  linkUrl.value = "";
  linkText.value = "";
  linkType.value = linkTypeOptions.value[0]?.value || "web";
};

// 处理移除链接
const handleRemove = () => {
  if (!editor?.value) return;

  editor.value.chain().focus().unsetLink().run();

  // 关闭对话框
  showDialog.value = false;
  linkUrl.value = "";
  linkText.value = "";
  linkType.value = linkTypeOptions.value[0]?.value || "web";
};
</script>

<style scoped lang="scss">
.link-type-option-item {
  display: flex;
  align-items: center;
  gap: 6px;
}

.link-type-option-icon {
  font-size: 14px;
  color: var(--editor-text-color);
}

.form-hint {
  font-size: var(--editor-font-size-small, 12px);
  color: var(--editor-text-color-secondary, var(--editor-text-color));
}
</style>
